#pragma once
#include <iostream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <jsoncpp/json/json.h>

#define SEP " "
#define SEP_LEN strlen(SEP) // 不敢使用sizeof()
#define LINE_SEP "\r\n"
#define LINE_SEP_LEN strlen(LINE_SEP) // 不敢使用sizeof()

enum
{
    OK = 0,
    DIV_ZERO,
    MOD_ZERO,
    OP_ERROR
};

// "x op y" -> "content_len"\r\n"x op y"\r\n
// "exitcode result" -> "content_len"\r\n"exitcode result"\r\n
std::string enLength(std::string &text)
{
    std::string send_string = std::to_string(text.size());
    send_string += LINE_SEP;
    send_string += text;
    send_string += LINE_SEP;
    return send_string;
}
// "content_len"\r\n"x op y"\r\n  ->"x op y"
bool deLength(const std::string &package, std::string *text)
{
    auto pos = package.find(LINE_SEP);
    if (pos == std::string::npos)
        return false;
    std::string text_len_string = package.substr(0, pos);
    int text_len = std::stoi(text_len_string);

    *text = package.substr(pos + LINE_SEP_LEN, text_len);
    return true;
}
class Request
{
public:
    Request() : _x(0), _y(0), _op(0)
    {
    }
    Request(int x, int y, char op) : _x(x), _y(y), _op(op)
    {
    }
    // "x op y"
    bool serialize(std::string *out)
    {
#ifdef MYSELF
        *out = "";
        std::string x_string = std::to_string(_x);
        std::string y_string = std::to_string(_y);

        *out = x_string;
        *out += SEP;
        *out += _op;
        *out += SEP;
        *out += y_string;
#else
        Json::Value root;
        root["first"] = _x;
        root["second"] = _y;
        root["oper"] = _op;

        Json::FastWriter writer;
        *out = writer.write(root); // 将JSON转换为字符串，并存入root
#endif
        return true;
    }

    bool deserialize(std::string &in)
    {
#ifdef MYSELF
        auto left_pos = in.find(SEP);
        auto right_pos = in.rfind(SEP);
        if (left_pos == std::string::npos || right_pos == std::string::npos)
            return false;

        // 拿到对应x y的字符串
        std::string x_string = in.substr(0, left_pos);
        std::string y_string = in.substr(right_pos + SEP_LEN);

        _x = std::stoi(x_string);
        _y = std::stoi(y_string);
        _op = in[left_pos + SEP_LEN];
#else
        Json::Value root;
        Json::Reader reader; // 用于解析 JSON 字符串
        reader.parse(in,root); // 解析输入流 in，将解析结果存入 root
        _x = root["first"].asInt();
        _y = root["second"].asInt();
        _op = root["oper"].asInt();
#endif
        return true;
    }
    ~Request()
    {
    }

public:
    // 这里就是协议的体现，为什么是"x op y"
    // "x op y"
    int _x;
    int _y;
    char _op;
};

class Response
{
public:
    Response() : _exitcode(0), _result(0)
    {
    }
    Response(int exitcode, int result) : _exitcode(exitcode), _result(result)
    {
    }
    bool serialize(std::string *out)
    {
#ifdef MYSELF
        *out = "";
        std::string ec_string = std::to_string(_exitcode);
        std::string res_string = std::to_string(_result);

        *out += ec_string;
        *out += SEP;
        *out += res_string;
#else
        Json::Value root;
        root["_exitcode"] = _exitcode;
        root["_result"] = _result;

        Json::FastWriter writer;
        *out = writer.write(root);
#endif
        return true;
    }
    bool deserialize(std::string &in)
    {
#ifdef MYSELF
        auto mid = in.find(SEP);
        if (mid == std::string::npos)
            return false;
        std::string ec_string = in.substr(0, mid);
        std::string res_string = in.substr(mid + SEP_LEN);
        if (ec_string.empty() || res_string.empty())
            return false;

        _exitcode = std::stoi(ec_string);
        _result = std::stoi(res_string);
#else
        Json::Value root;
        Json::Reader reader;
        reader.parse(in,root);
        _exitcode = root["_exitcode"].asInt();
        _result = root["_result"].asInt();
#endif
        return true;
    }

public:
    int _exitcode; // 0：计算成功，!0表示计算失败，具体是多少，定好标准
    int _result;   // 计算结果
};

// 对读取到的请求进行处理，确保读到的是一个完整的请求
// "content_len"\r\n"x op y"\r\n"content_len"\r\n"x op y"\r\n"content_len"\r\n"x op
bool recvPackage(int sock, std::string &inbuffer, std::string *req_text)
{
    char buffer[1024];
    while (true)
    {
        ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            // 读到的数据放入inbuffer
            inbuffer += buffer;
            // 寻找分隔符，第一个分隔符前面的数据是有效载荷的长度
            auto pos = inbuffer.find(LINE_SEP);
            if (pos == std::string::npos)
                continue;
            std::string text_len_string = inbuffer.substr(0, pos);
            int text_len = std::stoi(text_len_string);
            // 一个完整的报文的长度
            int total_len = text_len_string.size() + 2 * LINE_SEP_LEN + text_len;
            std::cout << "处理前#inbuffer: \n" << inbuffer << std::endl;

            if (inbuffer.size() < total_len)
            {
                std::cout << "你输入的消息，没有严格遵守我们的协议，正在等待后续的内容, continue" << std::endl;
                continue;
            }
            // 一定有一个完整的报文
            *req_text = inbuffer.substr(0, total_len);
            // 取走一个报文，将其删除
            inbuffer.erase(0, total_len);
            std::cout << "处理后#inbuffer:\n " << inbuffer << std::endl;
            break;
        }
        else
        {
            return false;
        }
    }
    return true;
}